#!/usr/bin/env python3
"""
Database initialization script for emobot project.
Creates all database tables using SQLAlchemy models.
"""

import sys
import time
from sqlalchemy import create_engine
from sqlalchemy.exc import OperationalError
from db.connection import DATABASE_URL, Base
from db.models.user_profile import UserProfile
from db.models.conversation_history import ConversationHistory
from db.models.environment_memory import EnvironmentMemory
from db.models.face_embedding import FaceEmbedding


def wait_for_database(max_retries=10, retry_interval=5):
    """Wait for database to be ready"""
    print(f"Waiting for database to be ready at {DATABASE_URL}")

    for attempt in range(max_retries):
        try:
            engine = create_engine(DATABASE_URL)
            with engine.connect() as conn:
                conn.execute("SELECT 1")
            print("Database is ready!")
            return True
        except OperationalError as e:
            print(
                f"Attempt {attempt + 1}/{max_retries}: Database not ready yet. Error: {e}"
            )
            if attempt < max_retries - 1:
                time.sleep(retry_interval)
            else:
                print("Failed to connect to database after maximum retries")
                return False


def create_tables():
    """Create all database tables"""
    print("Starting database table creation...")

    # Wait for database to be ready
    if not wait_for_database():
        print("Cannot create tables: Database not available")
        return False

    try:
        engine = create_engine(DATABASE_URL)
        print("Creating all tables...")

        # Create all tables
        Base.metadata.create_all(bind=engine)

        print("✅ All tables created successfully!")
        print("Created tables:")
        print("  - user_profiles")
        print("  - conversation_histories")
        print("  - environment_memories")
        print("  - face_embeddings")

        return True

    except Exception as e:
        print(f"❌ Error creating tables: {e}")
        return False


def main():
    """Main function"""
    print("=" * 50)
    print("Emobot Database Initialization")
    print("=" * 50)

    success = create_tables()

    if success:
        print("\n🎉 Database initialization completed successfully!")
        sys.exit(0)
    else:
        print("\n💥 Database initialization failed!")
        sys.exit(1)


if __name__ == "__main__":
    main()
